import axios from 'axios'
import { message } from 'ant-design-vue'
import pinia from '@/store'
import useUserStore from '@/store/modules/UserStore'
import useGlobalStore from '@/store/modules/globalStore'
import router from '@/router'
const request = axios.create({
  baseURL: import.meta.env.VITE_API_URL,
  timeout: 10000,
})
const { startRequest, endRequest } = useGlobalStore(pinia)
request.interceptors.request.use(
  (config) => {
    const { userInfo } = useUserStore()
    // config.headers['Content-Type'] = 'application/json;charset=UTF-8'
    if (userInfo.token) {
      config.headers['Authorization'] = `Bearer ${userInfo.token}`
    }
    startRequest()

    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

request.interceptors.response.use(
  (response) => {
    // 可以在这里对正常响应进行处理
    endRequest()
    return response
  },
  (error) => {
    // 处理响应错误
    const { response } = error
    if (response) {
      // 后端返回的状态码
      const { status } = response
      const { errno, msg: errorMessage } = response.data || {}
      const { logout } = useUserStore()
      switch (status) {
        case 401:
          message.error('未授权，请登录！')
          logout()
          router.push('/login')
          break
        case 404:
          message.error('请求的资源未找到！')
          break
        case 500:
          message.error('服务器内部错误，请稍后重试！')
          break
        default:
          // 处理其他状态码
          if (errno) {
            message.error(errorMessage || '发生错误，请重试！')
          } else {
            message.error('发生未知错误，请重试！')
          }
          break
      }
    } else {
      // 请求未发出时的处理
      message.error('网络错误，请检查您的网络连接！')
    }
    endRequest()
    return Promise.reject(error)
  }
)

export default request
